<style lang="scss" scoped>
.edit-container {
	border: 1px solid;
	border-radius: 4px;
	overflow: hidden;

	:deep(.w-e-scroll) {

		padding: 10px 0;

		p {
			margin: 0;
			line-height: 26px;
		}
	}

	:deep(.w-e-text-placeholder) {
		line-height: 14px;
	}
}
</style>
<template>
	<div class="edit-container custom-scrollbar" :style="{ borderColor: props.borderColor }">
		<Toolbar :style="{ borderBottom: '1px solid', borderColor: props.borderColor }" :editor="editorRef" :mode="mode" />
		<Editor v-model="model" :style="{ height: editHeight, overflowY: 'hidden' }" :defaultConfig="editorConfig"
			:mode="mode" @onCreated="handleCreated" />
	</div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { inject, onBeforeUnmount, shallowRef } from 'vue'

// 引入 css
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const http = inject('$http'), model = defineModel();

const emit = defineEmits(['uploaded']);

const props = defineProps({
	borderColor: {
		type: String,
		default: '#e2e2e2'
	},
	editHeight: {
		type: String,
		default: (window.innerHeight - 300) + 'px'
	}
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 编辑框模式
const mode = 'default';

// 上传图片文件大小限制
const imageSizeLimit = 2 * 1024 * 1024;

const editorConfig = {
	placeholder: '请输入内容...',
	maxLength: 5000,
	MENU_CONF: {
		uploadImage: {
			maxFileSize: imageSizeLimit,
			allowedFileTypes: ['image/png', 'image/gif', 'image/jpeg'],
			customUpload: customUploadHandle
		}
	}
}

const handleCreated = (editor) => {
	editorRef.value = editor // 记录 editor 实例，重要！
}

async function customUploadHandle(file, fn) {
	const limitNumber = (imageSizeLimit / (1024 * 1024)).toFixed(1);
	if (file.size > imageSizeLimit) {
		ElMessage({ type: "warning", message: "图片大小不得超过" + limitNumber + "M!__" + file.name });
		return false;
	}
	const res = await http.upload(file, 'notice');
	if (res && res.code === 200) {
		fn(res.data.full_path);
		emit('uploaded', res.data.full_path);
	}
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor == null) return
	editor.destroy()
})

</script>